﻿/* Copyright SysMates Technologies Pte. Ltd. */
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text.RegularExpressions;
using AppPressFramework;
using System.Globalization;
using System.Resources;
using ApplicationClasses;

namespace Application
{

    public partial class AppLogic
    {
        [Serializable]
        public class AppSessionData : SessionData
        {
            public bool isAdmin = false;
            public AppSessionData(AppPress a, string loginUserId, string email)
                : base(email, loginUserId, null)
            {
                this.email = email;
                this.isAdmin = Convert.ToBoolean(a.ExecuteInt32("Select Administrator From Application_Users Where Id = " + loginUserId));
            }
        }
        public const string ApplicationKey = "ahafhdjghitiyjtkgjkbfjrh";

        private static string CookiePreix(AppPress a)
        {
            return AppPress.GetBaseUrl();
        }
        public static void Init(AppPress a, LoginClass login)
        {
            login.Email.SetFocus();
            var emailCookie = a.Request.Cookies[CookiePreix(a) + "Email"];
            var passwordCookie = a.Request.Cookies[CookiePreix(a) + "Password"];
            if (emailCookie != null && passwordCookie != null)
            {
                login.Email.val = emailCookie.Value;
                login.Password.val = passwordCookie.Value;
                login.RememberMe.val = true;
                if (a.Request["FromSignout"] == null)
                    SetupSession(a, login);
                else
                    login.RememberMe.val = true;
            }

        }

        public static void OnClick(AppPress a, LoginClass.ForgotPasswordFieldClass emailField)
        {
            var login = (LoginClass)emailField.FormData;
            emailField.Validate();

            var f = new ForgotPasswordClass(a);
            f.Email.val = login.Email.val;
            //ForgotPasswordClass.Popup(a, null, null);
            f.Popup(a, new PopupParams { width = 500, title = "Forgot Password" });
        }


        public static void OnClick(AppPress a, ForgotPasswordClass.SendChangePasswordEmailFieldClass SendPassword)
        {
            SendPassword.Validate();
            var ForgotPassword = SendPassword.FormData;
            var email = ForgotPassword.Email.val;
            var userId = ValidateUserAndGetPassword(a, email);
            var secureUrl = a.GetSecureUrl("ChangePassword", userId, userId, new TimeSpan(2, 0, 0, 0, 0));
            var message = "<html><body style=\"font-family:Calibri; font-size:14px;\"> Dear User,<br/><br/>Click on the following link to change your password.<br/><br/><a href=\"" + secureUrl + "\">" + secureUrl + "<a/>" +
                            "<br/><br/><b> This link will expire in 2 days.</b>.<br/>If you have not raised this request then kindly contact Support Team.<br><br/> Reagrds,<br/>Administrator<br/></html></body>";
            a.SendEmail(email, null, "Forgot Password", message, null, null, true);
            a.ClosePopup();
            a.AlertMessage("Mail sent successfully. Please check your mail for link to change Password.");
        }

        private static string ValidateUserAndGetPassword(AppPress a, string email)
        {
            email = email.ToLower().Trim();
            string query = "Select Id From Application_Users Where (Email='" + email + "')  ";
            var userId = a.ExecuteString(query);
            if (userId == null)
                throw new AppPressException("No user with this email exists.");
            return userId;
        }

        public static void OnClick(AppPress a, LoginClass.LoginFieldClass loginField)
        {
            var login = loginField.FormData;
            var email = login.Email.val;
            var password = login.Password.val;
            SetupSession(a, login);

        }
        public static void Init(AppPress a, ChangePasswordClass ChangePassword)
        {
            ChangePassword.Name.val = Convert.ToString(a.ExecuteScalar("Select Name From Application_Users Where Id=" + ChangePassword.id));
        }
        public static void OnClick(AppPress a, ChangePasswordClass.ChangePasswordFieldClass Change)
        {
            var ChangePassword = Change.FormData;
            ChangePassword.Validate();
            if (ChangePassword.NewPassword.val != ChangePassword.ConfirmPassword.val)
                throw new AppPressException("New Password and Confirm Password do not Match");
            var regex = new Regex("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{6,20})");
            if (!regex.IsMatch(ChangePassword.NewPassword.val))
            {
                a.AlertMessage(
                    @"Password does not match following criteria
                    <ul>
                    <li>must contains one digit from 0-9</li>
                    <li>must contains one lowercase characters</li>
                    <li>must contains one uppercase characters</li>
                    <li>between 6 to 20 characters</li>
                    </ul>
                    ", "Password Error", 0, true);
                throw new AppPressException();
            }
            a.BeginTrans();
            try
            {
                if (DAOBasic.databaseType == DatabaseType.SqlServer)
                    a.ExecuteNonQuery("Update Application_Users Set Password=HASHBYTES('SHA1','" + ChangePassword.NewPassword.val.ToSqlEncodedString() + "') Where Id=" + ChangePassword.id);
                else
                    a.ExecuteNonQuery("Update Application_Users Set Password=SHA2('" + ChangePassword.NewPassword.val.ToSqlEncodedString() + "',256) Where Id=" + ChangePassword.id);
                a.AlertMessage("Your Password has been changed.");
                if (ChangePassword.PopupContainer != null)
                    a.ClosePopup(); // if it is a popup
                else
                    a.Redirect(LoginClass.formDefId, null, null);
                a.CommitTrans();
            }
            catch { a.RollbackTrans(); throw; }
        }
        private static void SetupSession(AppPress a, LoginClass login)
        {
            var email = login.Email.val;
            var password = login.Password.val;
            login.Validate();
            var employeeId = ValidateLogin(a, ref email, password);
            if (employeeId == null)
                return;
            a.sessionData = new AppSessionData(a, employeeId.ToString(), email);

            var emailCookie = a.Response.Cookies[CookiePreix(a) + "Email"];
            var passwordCookie = a.Response.Cookies[CookiePreix(a) + "Password"];
            if (login.RememberMe.val)
            {
                emailCookie.Value = email;
                passwordCookie.Value = password;
                emailCookie.Expires = passwordCookie.Expires = DateTime.Now.AddDays(5);
            }
            else
            {
                emailCookie.Expires = passwordCookie.Expires = DateTime.Now.AddDays(-1);
            }

            var redirectParams = new RedirectParams();
            redirectParams.urlParams += "&fromMenu=";
            HomeClass.Redirect(a, employeeId.ToString(), redirectParams);

        }

        private static int? ValidateLogin(AppPress a, ref string email, string password)
        {
            email = email.Trim().ToLower();
            var query = "Select id From Application_Users Where InActive = 0 and (Email='" + AppPress.EscapeMySQLString(email) + "')  ";
            if (DAOBasic.databaseType == DatabaseType.SqlServer)
                query += "and Password = HASHBYTES('SHA1','" + AppPress.EscapeMySQLString(password) + "')";
            else
                query += "and Password = SHA2('" + AppPress.EscapeMySQLString(password) + "',256)";
            var userId = a.ExecuteInt32(query);
            if (userId == null)
                a.AlertMessage("Wrong Email or Password.");
            return userId;
        }


    }
}